import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, message, Icon, Checkbox, Col, Select, Row } from 'antd';
import httpFetch from 'share/httpFetch'
import LanguageInput from 'components/template/language-input/language-input'
import menuRoute from 'routes/menuRoute'
import config from 'config'
import chooserData from 'share/chooserData'
import ListSelector from 'components/list-selector'
import BasicInfo from 'components/basic-info'
import cashService from "./cash-transaction-class-service"
import ResizeTable from 'components/resize-table';
const Option = Select.Option;

class CashTransactionClassDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      updateState: false,
      saving: false,
      loading: true,
      editing: false,
      setOfBookId: -1,
      infoList: [
        {type: 'input', id: 'setOfBookName',required: true, disabled: true, label: `${messages('pay-setting.key1'/*账套*/)}`}, //账套
        {type: 'input', id: 'typeName',required: true, disabled: true, label: messages('pay-setting.key7'/*现金事务类型*/) }, /*现金事务类型代码*/
        {type: 'input', id: 'classCode',required: true, disabled: true, label: messages('pay-setting.key8'/*现金事务分类代码*/) }, /*现金事务分类代码*/
        {type: 'switch', id: 'isEnabled', label: messages('common.column.status') +" :"/*状态*/},
      ],
      classData: {},
      data: [],
      cashFlowItemData: {
          saveUrl: `${config.payUrl}/api/cash/default/flowitems/batch`,
          url: `${config.payUrl}/api/cash/default/flowitems/query`,
          selectorItem: chooserData['cash_flow_item'],
          columns: [
            {title: messages('pay-setting.key2'/*现金流量项代码*/), dataIndex: "flowCode", width: '30%'},
            {title: messages('pay-setting.key3'/*现金流量项名称*/), dataIndex: "description", width: '40%'},
            {title: messages('pay-setting.key10'/*默认*/), dataIndex: "defaultFlag", width: '15%', render: (defaultFlag, record) => <Checkbox onChange={(e) => this.onChangeDefault(e, record)} checked={record.defaultFlag}/>},
            {title: messages('pay-setting.key11'/*启用*/), key: 'isEnabled', width: '15%', render: (isEnabled, record) => <Checkbox onChange={(e) => this.onChangeEnabled(e, record)} checked={record.isEnabled}/>}
          ]
      },
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      showListSelector: false,
      newData: [],
      cashTransactionClass: menuRoute.getRouteItem('cash-transaction-class', 'key'),  //现金事务的页面项
      writeOffList: [],
      i18n: []
    };
  }

  onChangeDefault = (e, record) => {
    this.setState({loading: true});
    record.defaultFlag = e.target.checked;
    httpFetch.put(`${config.payUrl}/api/cash/default/flowitems`, record).then(() => {
      this.getList().then(response => {
        this.setState({loading: false})
      });
    })
  };

  onChangeEnabled = (e, record) => {
    this.setState({loading: true});
    record.isEnabled = e.target.checked;
    httpFetch.put(`${config.payUrl}/api/cash/default/flowitems`, record).then(() => {
      this.getList().then(response => {
        this.setState({loading: false})
      });
    })
  };

  componentWillMount(){
    httpFetch.get(`${config.payUrl}/api/cash/transaction/classes/${this.props.params.classId}`).then(response => {
      let data = response.data;
      let infoList = this.state.infoList;
      data.typeCode === 'PREPAYMENT' && infoList.splice(4, 0, {
        type: 'select', id: 'prePaymentCode', required: true, disabled: false, label: messages('pay-setting.key68')/*预付款控制类型*/,
        options: [
          {label: messages('pay-setting.key65')/*不控制*/, value: 1001},
          {label: messages('pay-setting.key66')/*同类型控制*/, value: 1002},
          {label: messages('pay-setting.key67')/*全控制*/, value: 1003}
        ]
      },{
        type: 'select', id: 'isCompulsoryWriteOff', required: true, label: messages('pay-setting.key72')/*强制核销控制类型*/,
        options: [
          {label: messages('pay-setting.key73')/*强制核销*/, value: '1'},
          {label: messages('pay-setting.key74')/*不强制核销*/, value: '0'},
        ]
      });
      data.typeCode === 'PREPAYMENT' && (data.isCompulsoryWriteOff = data.isCompulsoryWriteOff ? '1' : '0');
      if(data.writeOffType){
        data.writeOffId = data.writeOffId ? data.writeOffId.split(',') : [];
      }
      this.setState({
        classData: data,
        setOfBookId: data.setOfBookId,
        infoList,
        i18n: data.i18n && data.i18n.description || [{language: 'zh_cn', value: data.description}, {language: 'en', value: ''}]
      },() => {
        const { classData } = this.state;
        if(classData.writeOffType){
          cashService.getWriteOffList(classData.setOfBookId).then(res => {
            this.setState({writeOffList: res.data})
          }).catch(e => {
            message.error(e.response.data.message)
          });
        }
      });
    });
    this.getList();
  }

  handleChangeType = value => {
    const {classData} = this.state;
    classData.writeOffType = value;
    classData.writeOffId = [];
    this.setState({classData,  updateState: false });
  };

  handleChangeId = value => {
    const {classData} = this.state;
    classData.writeOffId = value;
    this.setState({classData,  updateState: false });
  };

  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  getList = () => {
    const { cashFlowItemData, page, pageSize } = this.state;
    let url = cashFlowItemData.url;
    if(url){
      return httpFetch.get(`${url}?transactionClassId=${this.props.params.classId}&page=${page}&size=${pageSize}`).then(response => {
        response.data.map((item, index)=>{
          item.key = item.id ? item.id : index;
        });
        this.setState({
          data: response.data,
          loading: false,
          pagination: {
            total: Number(response.headers['x-total-count']),
            onChange: this.onChangePager,
            current: this.state.page + 1
          }
        })
      })
    }
  };


  handleNew = () => {
    this.setState({ showListSelector: true })
  };

  handleAdd = (result) => {
    this.setState({
      newData: result.result,
      showListSelector: false
    }, () => {
      this.handleSave();
    })
  };

  handleCancel = () => {
    this.setState({ showListSelector: false })
  };

  handleSave = () => {
    const { cashFlowItemData, newData } = this.state;
    let paramList = [];
    newData.map(item => {
      let flowItem = {};
      flowItem.cashFlowItemId = item.id;
      flowItem.transactionClassId = this.props.params.classId;
      flowItem.defaultFlag = false;
      flowItem.isEnabled = true;
      paramList.push(flowItem);
    });
    this.setState({saving: true}, ()=>{
      httpFetch.post(cashFlowItemData.saveUrl, paramList).then(response => {
        message.success('添加成功');
        this.setState({
          newData: [],
          page: 0,
          saving: false
        }, () => {
          this.getList();
        })
      }).catch(e => {
        this.setState({ editing: false });
        if(e.response){
          message.error(`添加失败,${e.response.data.validationErrors[0].message}`);
        }
      });
    })
  };

  updateHandleInfo = (params) => {
    const { classData, i18n } = this.state;
    params.prePaymentCode && params.prePaymentCode === messages('pay-setting.key65') && (params.prePaymentCode = '1001');
    params.prePaymentCode && params.prePaymentCode === messages('pay-setting.key66') && (params.prePaymentCode = '1002');
    params.prePaymentCode && params.prePaymentCode === messages('pay-setting.key67') && (params.prePaymentCode = '1003');
    params.isCompulsoryWriteOff && (params.isCompulsoryWriteOff = params.isCompulsoryWriteOff === '1');
    params.description = i18n.filter(item => item.language === 'zh_cn')[0].value;
    Array.isArray(classData.writeOffId) && (params.writeOffId = classData.writeOffId.length > 0 ? classData.writeOffId.join(',') : '');
    params.i18n = {
      description: i18n
    };
    this.setState({ editing: true });
    httpFetch.put(`${config.payUrl}/api/cash/transaction/classes`, Object.assign({}, this.state.classData, params)).then(response => {
      message.success('修改成功');
      let data = response.data;
      let infoList = this.state.infoList;
      if(data.typeCode === 'PREPAYMENT'){
        data.isCompulsoryWriteOff = data.isCompulsoryWriteOff ? '1' : '0';
      }
      if(data.writeOffType){
        data.writeOffId = data.writeOffId ? data.writeOffId.split(',') : [];
      }
      this.setState({
        classData: data,
        updateState: true,
        editing: false,
        infoList,
        i18n: data.i18n && data.i18n.description || [{language: 'zh_cn', value: data.description}, {language: 'en', value: ''}]
      });
    }).catch(e => {
      if(e.response){
        message.error(`${messages('common.save.filed')}, ${e.response.data.validationErrors[0].message}`);
      }
      this.setState({ editing: false })
    });
  };

  handlePeriodSetNameChange = (value, i18n) => {
    this.setState({ i18n });
  };

  render(){
    const { infoList, classData, cashFlowItemData, loading, pagination, data, showListSelector, saving, updateState,
      editing, i18n } = this.state;
    const { language } = this.props;
    const styleObj = { lineHeight: '25px', color: 'rgba(0,0,0,0.65)', fontSize: '14px' };
    let zh_value = i18n.filter(item => item.language === language.code).length > 0 ? i18n.filter(item => item.language === language.code)[0].value : undefined;
    let extraFields = [
      <div>
        <Row style={styleObj}>
          <Row>{messages('pay-setting.key9'/*现金事物分类名称*/)}：</Row>
        </Row>
        <div>
          <LanguageInput
            i18nName={i18n}
            isEdit={true}
            value={zh_value}
            nameChange={this.handlePeriodSetNameChange}
          />
        </div>
      </div>
    ], extraInfo = [
      { type: 'input', id: 'description',required: true, label: messages('pay-setting.key9'/*现金事物分类名称*/), value: zh_value }
    ];
    if(classData.typeCode === 'PAYMENT'){
      extraInfo.push({ label: messages('pay-setting.key75')/*核销对象*/,
        type: 'select',
        options: [{ value: '1', label: messages('common.all')/*全部*/},{ value: '2', label: messages('pay-setting.key76')/*部分*/}],
        id: 'writeOffType'});
      extraFields.push(<div>
        <Row style={styleObj}>
          <Col span={6}>{messages('pay-setting.key77')/*核销对象：*/}</Col>
        </Row>
        <div>
          <Col span={6}>
            <Select placeholder={messages('common.please.select')}
                    value={classData.writeOffType}
                    onChange={value => this.handleChangeType(value)}>
              <Option key={'1'}>{messages('common.all')/*全部*/}</Option>
              <Option key={'2'}>{messages('pay-setting.key76')/*部分*/}</Option>
            </Select>
          </Col>
          <Col span={16} offset={2}>
            <Select mode='multiple'
                    value={classData.writeOffId}
                    disabled={classData.writeOffType === '1'}
                    placeholder={messages('common.please.select')}
                    onChange={(value) => this.handleChangeId(value)}>
              {this.state.writeOffList.map(item => {
                return <Option key={item.id}>{item.description}</Option>
              })}
            </Select>
          </Col>
        </div>
      </div>);
    }
    return (
      <div>
        <BasicInfo infoList={infoList}
                   extraFieldsIndex={3}
                   infoData={classData}
                   extraInfo={extraInfo}
                   extraFields={extraFields}
                   updateHandle={this.updateHandleInfo}
                   updateState={updateState}
                   loading={editing}/>
        <div className="table-header">
          <div className="table-header-title">共搜索到 {pagination.total} 条数据</div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew} loading={saving}>添 加</Button>
          </div>
        </div>
        <ResizeTable
          columns={cashFlowItemData.columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          size="middle"/>

        <a className="back" onClick={() => {this.context.router.push(this.state.cashTransactionClass.url);}}><
          Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')/*返回*/}
        </a>

        <ListSelector visible={showListSelector}
                      onOk={this.handleAdd}
                      onCancel={this.handleCancel}
                      selectorItem={cashFlowItemData.selectorItem}
                      extraParams={cashFlowItemData.extraParams ? cashFlowItemData.extraParams : {setOfBookId: this.state.setOfBookId,isEnabled: true}}/>
      </div>
    )
  }

}

CashTransactionClassDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

export default connect(mapStateToProps)(CashTransactionClassDetail);
